package top.xtcoder.jdcbase.base.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;

import top.xtcoder.jdcbase.base.common.Funs;

@Service
public class GridfsService {
	@Autowired
	private GridFsTemplate gridFsTemplate;
	
	@Autowired
	private GridFSBucket gridFSBucket;
	
	public String upload(MultipartFile file) throws IOException {
		return upload(file.getBytes(), file.getOriginalFilename(), file.getContentType());
	}
	
	public String replace(byte[] fileByte,
			String id,
			String originalName,
			String contentType) throws IOException {
		Query query = new Query(Criteria.where("_id").is(id));
		gridFsTemplate.delete(query);
		return upload(fileByte, originalName, contentType);
	}
	
	public String upload(byte[] fileByte,
			String originalName,
			String contentType) throws IOException {
		String fileSuffix = originalName.substring(originalName.lastIndexOf(".")).toLowerCase();
		String fileName = Funs.getFileNameBySm3()+fileSuffix;
		
		DBObject metaData = new BasicDBObject();
		metaData.put("sourceName", originalName);
		metaData.put("contentType", contentType);
		InputStream inputStream = new ByteArrayInputStream(fileByte);
		ObjectId objectId = gridFsTemplate.store(inputStream, fileName, contentType, metaData);
		
		return objectId.toString();
	}
	
	public byte[] getFile(GridFSFile gridFsFile) throws IllegalStateException, IOException {
		GridFSDownloadStream gridFS = gridFSBucket.openDownloadStream(gridFsFile.getObjectId());
		GridFsResource gridFsResource = new GridFsResource(gridFsFile, gridFS);
		byte[] fileBdata = IOUtils.toByteArray(gridFsResource.getInputStream());
		return fileBdata;
	}
}
